package com.ls.lserp.modules.order.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.FileUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.SystemPath;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.BigConsumption;
import com.ls.lserp.modules.order.entity.BigcargoStyle;
import com.ls.lserp.modules.order.entity.BigcargoStyleFitProperty;
import com.ls.lserp.modules.order.service.BigcargoStyleService;
import com.ls.lserp.modules.order.service.BigConsumptionService;
import com.ls.lserp.modules.sys.entity.Dict;
import com.ls.lserp.modules.sys.utils.DictUtils;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/bigcargo/consumption")
public class BigConsumptionController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private BigConsumptionService bigConsumptionService;

	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public BigConsumption get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {

			// 执行查询语句 查询基本信息
			return bigConsumptionService.get(Long.parseLong(id));
		} else {

			// 若为空，实例化
			return new BigConsumption();
		}

	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("bigcargo:consumption:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 返回页面地址
		return "modules/order/bigConsumption";
	}

	/**
	 * @Title: 画面一览
	 * @Description: list
	 * @param bigConsumption
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws ResourceException
	 */
	@RequiresPermissions("bigcargo:consumption:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(BigConsumption bigConsumption, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "bigConsumption");

		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		searchParam.append("&unitCostNo=");
		searchParam.append(bigConsumption.getUnitCostNo());
		searchParam.append("&styleNo=");
		searchParam.append(bigConsumption.getStyleNo());
		searchParam.append("&styleNameCn=");
		searchParam.append(bigConsumption.getStyleNameCn());
		searchParam.append("&dateFrom=");
		searchParam.append(bigConsumption.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(bigConsumption.getDateTo());
		/*
		 * searchParam.append("&userId=");
		 * searchParam.append(bigConsumption.getUserId());
		 */
		searchParam.append("&tabPageStatus=");
		searchParam.append(bigConsumption.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());

		// 查询一览页面数据
		Page<BigConsumption> page = bigConsumptionService.findList(new Page<BigConsumption>(request, response),
				bigConsumption);
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try {
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("bigConsumptions", page.getList());
			map.put("pageNo", page.getPageNo());
			map.put("pageSize", page.getPageSize());
			map.put("springMacroRequestContext", new RequestContext (request));
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("bigConsumption.ftl"), map);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}

		listMap.put("bigConsumption", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}

	/**
	 * 进入查看页面
	 * 
	 * @param bigConsumption
	 * @param model
	 * @return
	 */
	@RequiresPermissions("bigcargo:consumption:view")
	@RequestMapping(value = "show")
	public String show(BigConsumption bigConsumption, Model model) {

		// bigConsumption = bigConsumptionService.get(bigConsumption);
		String flag = bigConsumption.getEditFlag();
		bigConsumption = bigConsumptionService.findBigConsumption(bigConsumption);
		bigConsumption.setEditFlag(flag);
		// 将查询结果赋值mvc model层返回jsp页面
		model.addAttribute("bigConsumption", bigConsumption);

		// 返回页面地址
		return "modules/order/bigConsumptionShow";
	}

	/**
	 * 编辑大货单耗窗口
	 * 
	 * @return
	 */

	@RequestMapping(value = "edit")
	public String edit(BigConsumption bigConsumption, HttpServletRequest request, HttpServletResponse response,
			Model model) {

		bigConsumption = bigConsumptionService.findBigConsumption(bigConsumption);

		model.addAttribute("bigConsumption", bigConsumption);
		return "modules/order/bigConsumptionCreate";

	}

	/**
	 * 创建大货单耗窗口
	 * 
	 * @return
	 */

	@RequestMapping(value = "create")
	public String create(BigConsumption bigConsumption, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		/*
		 * String flag = bigConsumption.getEditFlag(); bigConsumption =
		 * bigConsumptionService.findStyleMaterialList(bigConsumption);
		 * bigConsumption.setEditFlag(flag);
		 */
		bigConsumption.preInsert();
		model.addAttribute("bigConsumption", bigConsumption);
		return "modules/order/bigConsumptionCreate";

	}

	/**
	 * 保存大货单耗
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("bigcargo:consumption:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(BigConsumption bigConsumption, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if (bigConsumption.getId() != null) {
			// 编辑数据
			// 判断数据是否删除
			BigConsumption bigConsumptionNew = get(bigConsumption.getId().toString());
			// 判断数据是否删除
			if (bigConsumptionNew == null || BaseEntity.DEL_FLAG_DELETE.equals(bigConsumptionNew.getDeleteFlag())) {
				// 返回提示信息
				return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
			}

			// 排他处理
			if (bigConsumption.getVersion() == get(bigConsumption.getId().toString()).getVersion()) {

				// 版本号加1
				bigConsumption.setVersion(bigConsumption.getVersion() + 1);
			} else {

				// 返回提示信息
				return renderString(response, AjaxDone.error(getText("warehouse_edit_save_msg_fail")));
			}
		}

		// 保存数据
		bigConsumptionService.saveBigConsumption(bigConsumption);

		// 保存成功返回提示信息
		return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName("warehouse_edit_save_msg_success")));

	}

	/**
	 * 查看一条款式信息
	 * 
	 * @return
	 */
	@RequiresPermissions("bigcargo:consumption:view")
	@RequestMapping(value = "getStyle")
	@ResponseBody
	public String getStyle(BigConsumption bigConsumption, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		bigConsumption = bigConsumptionService.getStyle(bigConsumption);
		listMap.put("styleNo", bigConsumption.getStyleNo());
		listMap.put("styleNameCn", bigConsumption.getStyleNameCn());
		return renderString(response, listMap);

	}

	/**
	 * 联动返回单耗
	 * 
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "unitCost")
	@ResponseBody
	public String unitCost(String code, Model model, HttpServletResponse response) {

		List<BigConsumption> unitCostList = bigConsumptionService.findUnitCostList(Long.parseLong(code));

		return renderString(response, unitCostList);

	}

	/**
	 * 联动返回面料
	 * 
	 * @param code
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "material")
	@ResponseBody
	public String material(String code, Model model, HttpServletRequest request, HttpServletResponse response) {
		Map<Object, Object> listMap = new HashMap<Object, Object>();

		BigConsumption bigConsumption = bigConsumptionService.getUnitCost(Long.parseLong(code));
		List<BigConsumption> materialList = bigConsumption.getBigConsumptionMaterialList();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "materialList");
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try {
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("bigStyleMaterialLists", materialList);
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("bigStyleMaterialList.ftl"), map);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}

		listMap.put("materialList", strHtml);
		listMap.put("unitCostLossRate", bigConsumption.getUnitCostLossRate());
		listMap.put("unitCostMiddleStandard", bigConsumption.getUnitCostMiddleStandard());
		listMap.put("unitCost", bigConsumption.getUnitCost());
		listMap.put("unitCostRemark", bigConsumption.getUnitCostRemark());
		// ajax返回结果
		return renderString(response, listMap);
	}

	/**
	 * 款式联动返回面料
	 * 
	 * @param code
	 * @param model
	 * @return
	 */

	@RequiresPermissions("bigcargo:consumption:view")
	@RequestMapping(value = { "findMaterial" })
	@ResponseBody
	public String findMaterial(String code, Model model, HttpServletRequest request, HttpServletResponse response) {

		Map<Object, Object> listMap = new HashMap<Object, Object>();
		BigConsumption bigConsumption = bigConsumptionService.findMaterialList(Long.parseLong(code));
		List<BigConsumption> materialList = bigConsumption.getBigConsumptionMaterialList();

		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "materialList");
		String strUri = request.getContextPath() + Global.getAdminPath();
		String strHtml = "";
		try {
			Map<String, Object> map = new HashedMap();
			map.put("adminUri", strUri);
			map.put("bigStyleMaterialLists", materialList);
			strHtml = FreeMarkerTemplateUtils
					.processTemplateIntoString(freemarkerConfiguration.getTemplate("bigStyleMaterialList.ftl"), map);
		} catch (Exception e) {
			// 记录日志
			logger.error(e.getMessage(), e);
		}

		listMap.put("materialList", strHtml);

		// ajax返回结果
		return renderString(response, listMap);
	}

}
